import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class PhotoViewGalleryScreen extends StatefulWidget {
  List dataArr = [];
  int index = 0;
  String? heroTag;
  PageController? controller;

  PhotoViewGalleryScreen(
      {Key? key,
      required this.dataArr,
      required this.index,
      this.controller,
      this.heroTag})
      : super(key: key) {
    controller = PageController(initialPage: index);
  }

  @override
  _PhotoViewGalleryScreenState createState() => _PhotoViewGalleryScreenState();
}

class _PhotoViewGalleryScreenState extends State<PhotoViewGalleryScreen> {
  int currentIndex = 0;

  static Future<void> saveImage(String imageUrl, {bool isAsset: false}) async {
    try {
      if (imageUrl == null) {
        Fluttertoast.showToast(
            msg: '保存失败，图片不存在！',
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.black87,
            textColor: Colors.white,
            fontSize: 14.0);
        throw '';
      }

      /// 权限检测
      PermissionStatus storageStatus = await Permission.storage.status;
      if (storageStatus != PermissionStatus.granted) {
        storageStatus = await Permission.storage.request();
        if (storageStatus != PermissionStatus.granted) {
          Fluttertoast.showToast(
              msg: '无法存储图片，请先授权！',
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.black87,
              textColor: Colors.white,
              fontSize: 14.0);
          throw '';
        }
      }

      /// 保存的图片数据
      var response = await Dio()
          .get(imageUrl, options: Options(responseType: ResponseType.bytes));
      final result =
          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      Fluttertoast.showToast(
          msg: (result == null || result == '') ? '图片保存失败' : "保存成功~",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black87,
          textColor: Colors.white,
          fontSize: 14.0);
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    currentIndex = widget.index;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    widget.controller!.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Stack(
          children: <Widget>[
            InkWell(
              child: Container(
                color: Colors.black,
                child: PhotoViewGallery.builder(
                  scrollPhysics: const BouncingScrollPhysics(),
                  builder: (BuildContext context, int index) {
                    return PhotoViewGalleryPageOptions(
                      imageProvider: NetworkImage(widget.dataArr[index].image),
                      initialScale: PhotoViewComputedScale.contained * 1.0,
                      // heroAttributes: PhotoViewHeroAttributes(tag: widget.images[index].id),
                      // heroAttributes: widget.heroTag.isNotEmpty?PhotoViewHeroAttributes(tag: widget.heroTag):null,
                    );
                  },
                  itemCount: widget.dataArr.length,
                  loadingBuilder: (context, event) => Center(
                    child: Container(
                      width: 30.0,
                      height: 30.0,
                      child: CircularProgressIndicator(
                        value: event == null
                            ? 0
                            : event.cumulativeBytesLoaded /
                                event.expectedTotalBytes!,
                        color: AppColors.yellow,
                        strokeWidth: 3,
                      ),
                    ),
                  ),
                  backgroundDecoration: null,
                  pageController: widget.controller,
                  enableRotation: true,
                  onPageChanged: (index) {
                    setState(() {
                      currentIndex = index;
                    });
                  },
                ),
              ),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
            Positioned(
              top: MediaQuery.of(context).padding.top + 15,
              width: MediaQuery.of(context).size.width,
              child: Center(
                child: RichText(
                  text: TextSpan(
                    children: <TextSpan>[
                      TextSpan(
                        text: '${currentIndex + 1}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 22.0,
                          fontStyle: FontStyle.italic,
                        ),
                      ),
                      TextSpan(
                        text: '/${widget.dataArr.length}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.0,
                          fontStyle: FontStyle.italic,
                          // fontStyle: FontStyle.italic,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Positioned(
              //右上角关闭按钮
              left: 10,
              top: MediaQuery.of(context).padding.top,
              child: IconButton(
                icon: Image.asset(
                  'assets/images/common/tab_icon_back.png',
                  width: 20,
                  height: 20,
                  color: Colors.white,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ),
            Positioned(
              bottom: 30 + MediaQuery.of(context).padding.bottom,
              width: MediaQuery.of(context).size.width,
              child: Container(
                padding: EdgeInsets.only(left: 15, right: 15),
                child: Text(
                  widget.dataArr[currentIndex].content,
                  strutStyle: StrutStyle(
                      forceStrutHeight: true, height: 0.8, leading: 1),
                  style: TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
            ),
            Positioned(
                bottom: 80,
                right: 10,
                child: TextButton(
                  child: Container(
                    alignment: Alignment.center,
                    width: 66,
                    height: 30,
                    decoration: BoxDecoration(
                      color: Colors.grey,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Text(
                      '保存本地',
                      style: TextStyle(fontSize: 14, color: Colors.black),
                    ),
                  ),
                  onPressed: () {
                    saveImage(widget.dataArr[currentIndex].image);
                  },
                ))
          ],
        ),
      ),
    );
  }
}
